using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkillObject_Shard : SkillObject_Base
{
    public event Action onExplode;
    private Skill_Shard shardManager;
    [SerializeField] private GameObject explodePrefab;

    [Header("Shard Move Deatails")]
    private float moveSpeed;
    private Transform targetEnemy;
    private Coroutine coroutine;
    protected override void Update()
    {
        base.Update();
        if (targetEnemy == null)
            return;
        transform.position = Vector2.MoveTowards(transform.position, targetEnemy.position, moveSpeed * Time.deltaTime);
    }
    protected override void OnEnable()
    {
        base.OnEnable();
        targetEnemy = null;
    }
    public void SetupShard(Skill_Shard shardManager, float duration)
    {
        this.shardManager = shardManager;
        player = shardManager.player;
        damageScaleData = shardManager.damageScaleData;
        if (coroutine != null)
            StopCoroutine(coroutine);
        // coroutine = StartCoroutine(AutoDisable(duration));

        Invoke(nameof(Explode), duration);
    }
    public void SetupShard(Skill_Shard skillShard, bool canMove, float shardSpeed, float duration, Transform domainTarget = null)
    {
        shardManager = skillShard;
        player = shardManager.player;
        damageScaleData = skillShard.damageScaleData;

        if (coroutine != null)
            StopCoroutine(coroutine);
        // coroutine = StartCoroutine(AutoDisable(duration));

        if (canMove)
            MoveToClosestTarget(shardSpeed, domainTarget);

        Invoke(nameof(Explode), duration);
    }
    public void MoveToClosestTarget(float moveSpeed, Transform target = null)
    {
        this.moveSpeed = moveSpeed;
        targetEnemy = target != null ? target : GetClosestTargetEnemy();
    }
    private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.GetComponent<Enemy>() == null)
            return;
        Explode();
    }
    public void Explode()
    {
        if (gameObject.activeSelf == false)
        {
            CancelInvoke(nameof(Explode));
            return;
        }
        DamageEnemiesInRedius(targetCheck, checkRadius);
        //从对象池中取出爆炸特效
        GameObject explodeEffectPrefab = PoolManager.Instance.Release(explodePrefab, (explodePrefab) =>
        {
            explodePrefab.transform.position = transform.position;
            explodePrefab.transform.rotation = Quaternion.identity;
        });
        //还原颜色
        explodeEffectPrefab.GetComponentInChildren<SpriteRenderer>().color = shardManager.player.GetComponent<Entity_VFX>().GetElementColor(currentElementType);
        onExplode?.Invoke();
        PoolManager.Instance.Delease(gameObject);
    }
    // private IEnumerator AutoDisable(float duration)
    // {
    //     yield return new WaitForSeconds(duration);
    //     if (gameObject.activeSelf)
    //         Explode();
    // }
}
